package com.contour.forms;

import java.io.IOException;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.contour.util.DateFormatter;
import com.contour.util.Emailer;

public class ThirtyDayFreeTrialHandler extends HttpServlet {

	private static final long serialVersionUID = 348225213183901752L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// Do nothing; the request should not come as GET from form
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// handle request parameters
		if (req.getCharacterEncoding() == null) {
			req.setCharacterEncoding("UTF-8");
		}

		String name = req.getParameter("name");
		String email = req.getParameter("email");
		String phone = req.getParameter("phone");
		String address = req.getParameter("address");

		ServletContext context = getServletContext();

		String SMTPHost = context.getInitParameter("smtp");
		String fromAddress = context.getInitParameter("supportToAddress");
		String toAddress = context.getInitParameter("supportToAddress");
		String SMTPUsername = context.getInitParameter("SMTPUserName");
		String SMTPPassword = context.getInitParameter("SMTPPassword");

		String subject = "30 Day Free-Trial Request: "
				+ DateFormatter.getSimpleDateTimestamp(new Date(System
						.currentTimeMillis())) + " - " + name;

		String emailContent = "Name:" + name + "\n" + "Email:" + email + "\n"
				+ "Phone:" + phone + "\n" + "Address:" + address + "\n";

		Emailer emailer = new Emailer(SMTPHost, SMTPUsername, SMTPPassword);
		emailer.sendEmail(fromAddress, toAddress, subject, emailContent);

		RequestDispatcher dispatcher = context
				.getRequestDispatcher("/pages/thirtyDayFreeTrialSubmitSuccess.jsp");
		dispatcher.forward(req, resp);
	}
}
